import React, { useEffect, useState } from 'react'
import { Button, Checkbox, Form, Input } from 'antd'
import { useDispatch } from 'react-redux'

import { accessAdded } from '@/store/features/access/accessSlicer'
import { getAccess, login } from '@/service/user'
import styles from './index.module.scss'
import { useNavigate } from 'react-router-dom'

interface LoginForm {
  username?: string
  password?: string
  remember?: boolean
}

const Login: React.FC = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [loginForm] = useState<LoginForm>(JSON.parse(localStorage.getItem('login') as string) || {})
  const dispatch = useDispatch()

  useEffect(() => {
    const token = localStorage.getItem('token')
    if (token) {
      navigate('/dashboard')
    }
  }, [])

  const onFinish = async (values: any) => {
    if (values.remember) localStorage.setItem('login', JSON.stringify(values))
    if (!values.remember) localStorage.removeItem('login')
    Reflect.deleteProperty(values, 'remember')
    await login(values)
    localStorage.setItem('token', 'token')
    const access = await getAccess()
    dispatch(accessAdded(access))
    window.location.reload()
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  return (
    <div className={styles.login}>
      <div className={styles.left}></div>
      <div className={styles.right}>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            initialValue={loginForm.username}
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            initialValue={loginForm.password}
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            initialValue={loginForm.remember}
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
